package com.risetechnology.services;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.SQLException;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.risetechnology.common.Shared;
import com.risetechnology.data.Schedule;
import com.risetechnology.database.DbAdapter;
import com.risetechnology.database.DbHelper;

public class MyAlarmService extends Service {

	@Override
	public void onCreate() {
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		
		initDatabase();
		
		for (Schedule s : Shared.dbAdapter.getScheduleInFuture(Calendar.getInstance().getTimeInMillis())) {
			Intent myIntent = new Intent(getBaseContext(), AlertService.class);
	    	myIntent.putExtra("SCHEDULE_NAME", s.getTitle());
	    	myIntent.putExtra("SCHEDULE_TIME", s.getPreTime());
	    	
	    	PendingIntent pendingIntent = PendingIntent.getService(this, s.getId(), myIntent, 0);

			AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

			alarmManager.set(AlarmManager.RTC_WAKEUP, s.getReminderTime(), pendingIntent);
//			Toast.makeText(getBaseContext(), s.getTitle()+" => "+s.getReminderTime(), Toast.LENGTH_SHORT).show();
			
		}
	}

	private void initDatabase() {
		DbAdapter dbAdapter = new DbAdapter(this);
		File db = getDatabasePath(DbHelper.DATABASE_NAME);
		if (db.exists()) {
			dbAdapter.open();
		} else {
			try {
				dbAdapter.close();
				dbAdapter.open(getAssets().open(DbHelper.DATABASE_NAME));
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				dbAdapter.open();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Shared.dbAdapter = dbAdapter;
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

}